package com.sqfw.project.utils;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * 通过FTP上传文件
 *
 */
@Data
@Component
@PropertySource(value = {"classpath:ftp.properties"}, encoding = "utf-8")
@Slf4j
public class FTP2Tools {

    private static String host;
    private static int port;
    private static String username;
    private static String password;
    private static String workingPath;

    @Value("${ftp2.host}")
    public void setHost(String host){
        this.host = host;
    }
    @Value("${ftp2.port}")
    public void setPort(int port){
        this.port = port;
    }
    @Value("${ftp2.username}")
    public void setUsername(String username){
        this.username = username;
    }
    @Value("${ftp2.password}")
    public void setPassword(String password){
        this.password = password;
    }
    @Value("${ftp2.workingPath}")
    public void setWorkingPath(String workingPath){
        this.workingPath = workingPath;
    }


    /**
     * 通过ftp上传文件
     * @param inputStream 文件流
     * @param saveName 文件名称
     * @param ftpPath 上传文件的路径
     * @return
     * */
    public static String upload(InputStream inputStream, String saveName, String ftpPath) {
        FTPClient ftpClient = new FTPClient();
        //1 连接ftp
        if (connect(ftpClient, host, port, username, password)) {
            try {
                if (StringUtils.isBlank(ftpPath)) {
                    ftpPath = workingPath ;
                }
                log.info("ftp2上传文件路径path: {}", ftpPath);
                String[] pathArr = ftpPath.split("/");
                for (String pathStr : pathArr) {
                    if(StringUtils.isBlank(pathStr)){
                        continue;
                    }
                    //FTP创建文件夹需要循环创建
                    //2 检查工作目录是否存在
                    if (!ftpClient.changeWorkingDirectory(pathStr)) {
                        boolean b = ftpClient.makeDirectory(pathStr);
                        ftpClient.changeWorkingDirectory(pathStr);
                    }
                }

                // 3 检查是否上传成功
                if (storeFile(ftpClient, saveName, inputStream)) {
                    disconnect(ftpClient);
                    return ftpPath;
                }
            } catch (IOException e) {
                log.error("ftp2上传工作目录不存在");
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        return "";
    }

    /**
     * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                log.info("ftp2已关闭连接");
            } catch (IOException e) {
                log.error("ftp2关闭连接失败：{}", e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
        boolean flag = false;
        try {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            if (ftpClient.login(username, password)) {
                log.info("ftp2连接成功");
                ftpClient.setBufferSize(1024);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.setControlEncoding("UTF-8");
                flag = true;
            } else {
                log.error("ftp2连接失败，可能用户名或密码错误");
                try {
                    disconnect(ftpClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("ftp2连接失败，可能ip或端口错误");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param ftpClient
     * @param saveName        全路径。如/home/public/a.txt
     * @param fileInputStream 要上传的文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
        boolean flag = false;
        try {
            if (ftpClient.storeFile(saveName, fileInputStream)) {
                flag = true;
                log.info("ftp2上传成功");
                // 关闭连接
                disconnect(ftpClient);
            }
        } catch (IOException e) {
            log.error("ftp2上传失败: {}", e.getMessage());
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }

}
